package com.dy.core.utils;

import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.log4j.Logger;



public class ImageUtil {

	private static Logger logger = Logger.getLogger(ImageUtil.class);
	
	public static Properties properties = null;
	private static String UPLOAN_PATH = "";
	static {
		try {
			InputStream inputStream = ImageUtil.class.getClassLoader().getResourceAsStream("system.properties");
			
			properties = new Properties();
			properties.load(inputStream);
			
			UPLOAN_PATH = properties.getProperty("IMAGE_UPLOAN_PATH") != null ? properties.get("IMAGE_UPLOAN_PATH").toString() : "/data/dyimage";
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 相对路径
	 * @param module
	 * @param function
	 * @return
	 */
	public static String getImagePathDir(String module, String function) {
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
		return "/default/" + module + "/" + function + "/" + dateformat.format(new Date()) + "/";
	}

	/**
	 * 绝对路径
	 * @param imagePathDir
	 * @return
	 */
	public static String getImageRealPathDir(String imagePathDir) {
		return UPLOAN_PATH + imagePathDir;
	}
	
	/**
	 * 生成文件名
	 * @param fileName
	 * @return
	 */
	public static String generateFileName(String fileName) {
		return md5(fileName) + getExtensionName(fileName);
	}
	
	/**
	 * 获取文件扩展名 比如：.jpg
	 * @param filename
	 * @return
	 */
	public static String getExtensionName(String fileName) {
		if (fileName != null && fileName.length() > 0) {
			int dot = fileName.lastIndexOf('.');
			if ((dot > -1) && (dot < (fileName.length() - 1))) {
				return fileName.substring(dot);
			}
		}
		return fileName != null ? fileName : "";
	} 
	
	/**
	 * 根据文件名获取MD5串
	 * @param text
	 * @return
	 */
	public static String md5(String text) {
		if (text == null || text.length() < 1) {
			return "";
		}
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "";
		}

		byte[] byteArray = text.getBytes();
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(generateFileName("美国从柘城fsdfdsfdffdfdssd.jpg"));
	}
}
